package com.service.socket.server;

import org.jboss.netty.buffer.BigEndianHeapChannelBuffer;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;

import com.service.cache.CacheManager;
import com.service.other.FileConser;
import com.service.socket.process.R_Class_Abstract;
import com.service.socket.process.R_Class_Factory;
import com.service.socket.process.SendCommand;
import com.service.socket.protocol.CmdType;
import com.service.socket.protocol.CmdWord;
import com.service.socket.protocol.Packet;
import com.service.socket.protocol.Resolver;

public class VehicleChannelHandler extends SimpleChannelHandler {

	@Override
	public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		VehicleServer.instance().channelGroup.add(e.getChannel());
		ctx.sendUpstream(e);		
	}

	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		super.channelConnected(ctx, e);
	}

	@Override
	public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		ctx.sendUpstream(e);
	}

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception {
		BigEndianHeapChannelBuffer message = (BigEndianHeapChannelBuffer) e.getMessage();
		byte[] bytes = message.array();
		if (bytes != null && bytes.length > 0) {
			Packet packet = Resolver.parsePacket(bytes);
			if (packet != null) {
				System.out.println("receive:" + packet.getRawData());
				FileConser.save(packet.getDeviceNo(), packet.getRawData(), "receive");
				R_Class_Abstract rclass = R_Class_Factory.create(e.getChannel(), packet);
				if (rclass != null) {
					rclass.execute();
				}
			}
		}
	}

	/*
	 * 当I/O线程或ChannelHandler出现异常时，触发该监听
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
			throws Exception {
		e.getChannel().close();
		if (CacheManager.instance().activeChannel.containsKey(e.getChannel().getId())) {
			CacheManager.instance().activeChannel.remove(e.getChannel().getId());
		}
		for (String i : CacheManager.instance().sessionMap.keySet()) {
			if (CacheManager.instance().sessionMap.get(i) == e.getChannel().getId()) {
				CacheManager.instance().sessionMap.remove(i);
				Packet p = new Packet();
				p.cmdType=CmdType.COCLASS_LINK;
				p.cmdWord=CmdWord.COWORD_REG_LOGIN;
				p.status = CmdWord.STATUS_FAIL;
				p.setDeviceNo(i);
				SendCommand.sendCtrlUser(p);
				System.out.println("device[" + i + "] shut down.");
				break;
			}
		}
	}
}
